package org.assistant.common.jdbc.datasource;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.assistant.common.exception.InitDataSourceException;
import org.assistant.common.utils.ClassUtils;

public class DataSourceConfig {
	private static Properties dataSourceConfig = null;

	/**
	 * 该构造函数用于在JavaBean中加载datasource.cfg
	 */
	public DataSourceConfig() {
		// 加载数据源配置文件
		if (dataSourceConfig == null) {
			dataSourceConfig = new Properties();
			InputStream in = ClassUtils
				.getDefaultClassLoader().getResourceAsStream("/datasource.cfg");
			try {
				dataSourceConfig.load(in);
			} catch (IOException e) {
				e.printStackTrace();
				throw new InitDataSourceException("加载数据源配置时出错，请重启服务！");
			}
		}
	}

	/**
	 * 该构造函数用于在Servlet中加载datasource.cfg
	 * 
	 * @param servletContext
	 * @throws ServletException
	 */
	public DataSourceConfig(ServletContext servletContext)
			throws ServletException {
		// 加载数据源配置文件
		if (dataSourceConfig == null) {
			dataSourceConfig = new Properties();
			InputStream in = servletContext
				.getResourceAsStream("/config/datasource.cfg");
			try {
				dataSourceConfig.load(in);
			} catch (IOException e) {
				e.printStackTrace();
				throw new ServletException("加载数据源配置时出错，请重启服务！");
			}
		}
	}

	public boolean isJndi() {
		String jndi = dataSourceConfig.getProperty("JNDI");
		if (jndi == null || "".equals(jndi.trim())) {
			throw new IllegalArgumentException(
				"Property 'JNDI' must not be empty");
		}

		boolean flag = Boolean.getBoolean(jndi);
		return flag;
	}

	public String getDataSourceClassName() {
		return dataSourceConfig.getProperty("dataSourceClassName");
	}

	public String getDriverClassName() {
		return dataSourceConfig.getProperty("driverClassName");
	}

	public String getUrl() {
		return dataSourceConfig.getProperty("url");
	}

	public String getUsername() {
		return dataSourceConfig.getProperty("username");
	}

	public String getPassword() {
		return dataSourceConfig.getProperty("password");
	}

	public String getContext() {
		return dataSourceConfig.getProperty("context");
	}

	public String getJndiName() {
		return dataSourceConfig.getProperty("jndiName");
	}

	public void clear() {
		dataSourceConfig.clear();
	}
}
